import os, glob
from serial.tools.list_ports import comports


def choose_an_option(title, options):
	print(f'{title} List:')
	for index, option in enumerate(options, start=1):
		if index == 1:
			print(f'\x1b[32m  [{index}] {option}\033[0m')
		else:
			print(f'  [{index}] {option}')

	selected = None

	while True:
		try:
			selected = input('Choose an option: ')

			if selected == '':
				return options[0]

			selected = int(selected)

			assert type(selected) is int and 0 < selected <= len(options)
			
			return options[selected - 1]
		except KeyboardInterrupt:
			exit()
		except:
			pass

def run_esptool_shell():
	__CHIP     = '--chip auto'
	__PORT     = '--port {}'
	__BAUD     = '--baud 115200'
	__FIRMWARE = 'firmware.bin'

	if not os.path.exists(__FIRMWARE):
		print('- No firmware.bin found')
		os.system('pause')
		return

	port_list = []

	for port in comports():
		if not str(port).startswith('COM1 '):
			port_list.append(str(port))

	if len(port_list) == 0:
		print('- No Serial Port found')
		os.system('pause')
		return

	port = choose_an_option('Port', port_list)
	__PORT = __PORT.format(port.split(' - ')[0])

	__AIRISP = glob.glob('AirISP*\\AirISP-next.exe')

	if len(__AIRISP) > 0:
		__AIRISP = __AIRISP[0]

		write_command = f'{__AIRISP} {__CHIP} {__PORT} {__BAUD} --before default_reset --after hard_reset write_flash -e 0x08000000 {__FIRMWARE}'

		try:
			os.system(write_command)
		except OSError as ose:
			print(ose)
	else:
		print('- No AirISP-next.exe found')
		print('- Visit https://github.com/Air-duino/AirISP-next/releases')

	os.system('pause')


if __name__ == '__main__':
	print('\033[1;37mQiguang Light Board Flash Tool\n\033[0m')
	run_esptool_shell()
